﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace printimage
{
    class PrintHelper
    {
        Image m_img;
        bool m_canceled;
        public enum ResultCode
        {
            Unknown = 0,
            Succeeded = 1,
            InvalidParam = 2,
            InvalidFile = 3,
            PrinterInvalid = 4,
            UserCanceled = 5
        }
        public List<string> GetAllPrinters()
        {
            var ret = new List<string>();
            var count = PrinterSettings.InstalledPrinters.Count;
            for (int i = 0; i < count; i++)
            {
                ret.Add(PrinterSettings.InstalledPrinters[i]);
            }
            return ret;
        }

        private string getPrinterNameByIndex(int index)
        {
            var all = GetAllPrinters();
            if (index < 0 || index >= all.Count)
                return null;
            return all[index];
        }

        public ResultCode Print(string src , int printerNo)
        {
            string printername = getPrinterNameByIndex(printerNo - 1);
            if (string.IsNullOrEmpty(printername))
                return ResultCode.InvalidParam;
            PrintDocument pd = new PrintDocument();
            pd.PrinterSettings.PrinterName = printername;
            if (!pd.PrinterSettings.IsValid)
            {
                return ResultCode.PrinterInvalid;
            }
            try
            {
                m_img = Image.FromFile(src);
            }
            catch (Exception ){ }
            if (m_img == null)
            {
                return ResultCode.InvalidFile;
            }
            pd.PrintPage += Pd_PrintPage;
            pd.EndPrint += Pd_EndPrint;
            var ret = ResultCode.Unknown;
            m_canceled = false;
            try
            {
                pd.Print();
                m_img = null;
                ret = m_canceled ? ResultCode.UserCanceled : ResultCode.Succeeded;
            }
            catch (Exception) { }
            return ret;
        }

        private void Pd_EndPrint(object sender, PrintEventArgs e)
        {
            m_canceled = e.Cancel;
        }

        private void Pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(m_img , e.PageBounds);
        }
    }
}
